#include <my_header.h>
#include <string.h>

#define BUF_SIZE 4096

typedef struct student {
    int stu_id;
    char name[32];
    float score;
} student;

int copy_data(const char* path, const student* data);

int main(int argc, char *argv[]) {
    ARGS_CHECK(argc, 2);

    student s[3] = {
        {0, "zhangsan", 59},
        {1, "lisi", 79},
        {2, "wangwu", 99},
    };

    int ret = copy_data(argv[1], s);
    return ret;
}

int copy_data(const char* path, const student* data) {
    // 1. 打开文件（修正权限为0644）
    int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);
    ERROR_CHECK(fd, -1, "open");

    // 2. 写入数据（修正：直接写data指针指向的内容）
    ssize_t ret1 = write(fd, data, sizeof(student) * 3); // 写入3个结构体
    ERROR_CHECK(ret1, -1, "write");

    // 3. 重置文件指针
    off_t ret2 = lseek(fd, 0, SEEK_SET);
    ERROR_CHECK(ret2, -1, "lseek");

    // 4. 读取数据
    student read_data[3];
    ssize_t read_count = read(fd, &read_data, sizeof(read_data));
    ERROR_CHECK(read_count, -1, "read");

    // 5. 打印结果（修正循环次数）
    printf("学号\t姓名\t分数\n");
    printf("----------------\n");
    for(int i = 0; i < sizeof(read_data)/sizeof(student); i++) {
        printf("%d\t%s\t%.1f\n",
              read_data[i].stu_id,
              read_data[i].name,
              read_data[i].score);
    }
    
    close(fd);
    return 0;
}
